package com.will.client.adapter;

import com.will.client.NettyClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author 杨明智
 * @version:1.0
 * @create 2019年01月13日 12:27 PM
 * @description
 **/
@ChannelHandler.Sharable
public class MyInboundHandlerAdapter extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(MyInboundHandlerAdapter.class);

    private NettyClient client;

    public MyInboundHandlerAdapter(NettyClient client) {
        this.client = client;
    }

    /**
     * channel链路每次active的时候，将其连接的次数重新☞ 0
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        logger.info("当前链路已经激活。。。");
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("链接关闭");
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(new Runnable() {
            @Override
            public void run() {
                logger.info("链接关闭，,每2秒进行一次重连");
                client.createBootstrap(new Bootstrap(), eventLoop);
            }
        }, 2L, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }
}
